package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

import java.util.Date;

/**
 * @author alan
 */
public class ChapterExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    private EduChapterService eduChapterService;
    private String courseId;

    public ChapterExcelListener(EduChapterService eduChapterService, String id) {
        this.eduChapterService = eduChapterService;
        this.courseId = id;
    }


    /**
     * 逐行读取表
     *
     * @param excelSubjectData
     * @param analysisContext
     */
    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if (ObjectUtils.isNull(excelSubjectData)) {
            throw new GuliException(20001, "添加失败");
        }
        saveDate(excelSubjectData);
    }

    private void saveDate(ExcelSubjectData data) {

        EduChapter dbData =
                eduChapterService.lambdaQuery().eq(EduChapter::getTitle, data.getOneSubjectName()).eq(EduChapter::getCourseId, courseId)
                        .orderByDesc(EduChapter::getId).last("limit 1").one();
        Date now = new Date();

        if (ObjectUtils.isNull(dbData)) {
            EduChapter pEduChapter = new EduChapter();
            pEduChapter.setSort(eduChapterService.getNextSort("0", courseId))
                    .setPid("0")
                    .setCourseId(courseId)
                    .setTitle(data.getOneSubjectName())
                    .setGmtModified(now)
                    .setGmtCreate(now);
            eduChapterService.save(pEduChapter);

            EduChapter eduChapter = new EduChapter();
            eduChapter.setPid(pEduChapter.getId())
                    .setGmtCreate(now)
                    .setGmtModified(now)
                    .setCourseId(courseId)
                    .setTitle(data.getTwoSubjectName())
                    .setSort(eduChapterService.getNextSort(pEduChapter.getId(), courseId));
            eduChapterService.save(eduChapter);

        } else {
            EduChapter eduChapter = new EduChapter();
            eduChapter.setPid(dbData.getId())
                    .setGmtCreate(now)
                    .setCourseId(courseId)
                    .setGmtModified(now)
                    .setTitle(data.getTwoSubjectName())
                    .setSort(eduChapterService.getNextSort(dbData.getId(), courseId));
            eduChapterService.save(eduChapter);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
